package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplusdemo.mapper.RatingMapper;
import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.model.domain.Rating;
import com.example.mybatisplusdemo.model.domain.Review;
import com.example.mybatisplusdemo.mapper.ReviewMapper;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.model.dto.ReviewDTO;
import com.example.mybatisplusdemo.service.IRatingService;
import com.example.mybatisplusdemo.service.IReviewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatisplusdemo.service.IUserService;
import com.fasterxml.jackson.core.JsonParser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxp
 * @since 2025-07-04
 */
@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements IReviewService {
    @Autowired
    private ReviewMapper reviewMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IRatingService  ratingService;
    @Autowired
    private RatingMapper ratingMapper;
    @Autowired
    private IUserService userService;

    @Override
    public Page<ReviewDTO> listReviewsByUserId(Page<ReviewDTO> page, Long userId) {
        return reviewMapper.listReviewsByUserId(page, userId);
    }

    @Override
    public List<ReviewDTO> getChildReviewByParentId(Long parentId) {
        //根据父评论id查询子评论列表
        List<Review> reviewList = reviewMapper.selectChildReviewsByParentId(parentId);

        //将Review列表转换为ReviewDTO列表,填充User信息
        List<ReviewDTO> reviewDTOList = new ArrayList<>();
        for (Review review : reviewList) {
            ReviewDTO reviewDTO = new ReviewDTO();

            reviewDTO.setId(review.getId());
            reviewDTO.setUserId(review.getUserId());
            reviewDTO.setStoreId(review.getStoreId());
            reviewDTO.setContentText(review.getContentText());
            reviewDTO.setContentMedia(review.getContentMedia());
            reviewDTO.setParentId(review.getParentId());
            reviewDTO.setStatus(review.getStatus());
            reviewDTO.setCreatedAt(review.getCreatedAt());
            reviewDTO.setHidden(review.getHidden());
            reviewDTO.setDeleted(review.getDeleted());

            //根据评论用户id获取 User信息并设置到ReviewDTO
            User user = userService.getById(review.getUserId());
            reviewDTO.setUser(user);

            reviewDTOList.add(reviewDTO);
        }

        return reviewDTOList;
    }

    @Override
    public List<ReviewDTO> getReviewByStoreId(Long storeId) {
        //查询店铺下所有父评论
        List<Review> parentReviews = reviewMapper.selectParentReviewsByStoreId(storeId);

        List<ReviewDTO> result = new ArrayList<>();
        for (Review review : parentReviews) {
            ReviewDTO dto = new ReviewDTO();

            //复制评论基础信息到 DTO
            dto.setId(review.getId());
            dto.setUserId(review.getUserId());
            dto.setStoreId(review.getStoreId());
            dto.setContentText(review.getContentText());
            dto.setContentMedia(review.getContentMedia());
            dto.setParentId(review.getParentId());
            dto.setStatus(review.getStatus());
            dto.setCreatedAt(review.getCreatedAt());
            dto.setHidden(review.getHidden());
            dto.setDeleted(review.getDeleted());

            //查询评论对应的用户信息
            User user = userMapper.selectById(review.getUserId());
            dto.setUser(user);

            //查询评论对应的评分（假设一个评论对应一条评分）
            Rating rating = ratingMapper.selectByReviewId(review.getId());
            if (rating != null) {
                dto.setScore(rating.getScoreTotal()); //假设取综合评分，可根据需求调整
            }

            result.add(dto);
        }

        return result;
    }

    @Override
    public List<Long> listChildIdByParentId(Long parentId) {
        return reviewMapper.listChildIdByParentId(parentId);
    }



    @Override
    public boolean insertChildReview(ReviewDTO reviewDTO) {
        //将reviewDTO转为review
        Review review = reviewDTO.toReview();

        review.setCreatedAt(LocalDateTime.now()); //设置评论时间为当前时间
        review.setStatus((byte) 1);
        review.setHidden(false); //默认对他人可见
        review.setDeleted(false); //默认未删除

        //插入数据
        return save(review);
    }

    @Override
    public List<Review> getParentReviewsByUserId(Long userId) {
        // 调用Mapper方法查询父评论
        return reviewMapper.selectParentReviewsByUserId(userId);
    }

    @Override
    public boolean insertParentReview(ReviewDTO reviewDTO) {
        Review review = reviewDTO.toReview();

        review.setCreatedAt(LocalDateTime.now()); //设置评论时间为当前时间
        review.setStatus((byte) 1);
        review.setHidden(false); //默认对他人可见
        review.setDeleted(false); //默认未删除

       if (save(review)) {
           Rating rating = reviewDTO.getRating();
           rating.setReviewId(review.getId()); // ← 关键：用刚才生成的 review id
           rating.setDeleted(false);
           return ratingService.save(rating);
       }
       return false;
    }

//    @Override
//    public boolean insertParentReview(ReviewDTO reviewDTO) {
//        if (insertChildReview(reviewDTO)){
//            Rating rating = new Rating();
//            if (ratingService.save(reviewDTO.getRating())){
//                return  true;
//            }
//        }
//        return false;
//    }
}
